# -*- coding: UTF-8 -*-
import csv
import json
import os
import shutil
from enum import Enum


class ErrSource(Enum):
    CONTROLLER = 0
    SERVO = 1
    RIO_OR_EXTIO = 2
    SCB_OR_TOR_SENSOR = 3


root_dir = os.path.realpath(os.path.join(os.path.dirname(__file__), "../"))
for member in ErrSource:
    shutil.rmtree(root_dir + "/" + member.name, True)
    os.makedirs(root_dir + "/" + member.name)

# 打开CSV文件
with open("code.csv", "r") as csv_file:
    # 读取CSV数据
    csv_reader = csv.DictReader(csv_file)

    # 遍历每一行数据并生成JSON文件
    for row in csv_reader:
        # 使用文件名来创建唯一的JSON文件
        if row["errorcode"] == "":
            continue
        source = (int(row["errorcode"], 16) & 0x00F00000) >> 20
        filename = "../{}/{}.json".format(ErrSource(source).name, ("0x" + row["errorcode"][2:].zfill(8)))
        with open(filename, "w") as json_file:
            # 将每一行数据转换为JSON格式并写入文件
            json.dump(
                {
                    "errorcode": row["errorcode"],
                    "isShowConfirm": row["isShowConfirm"],
                    "isShowOTA": row["isShowOTA"],
                    "type": row["type"],
                    "zh": {"tittle": row["tittle.zh"], "description": row["description.zh"], "reason": row["reason.zh"], "action": row["action.zh"]},
                    "en": {"tittle": row["tittle.en"], "description": row["description.en"], "reason": row["reason.en"], "action": row["action.en"]},
                    "ja": {"tittle": row["tittle.ja"], "description": row["description.ja"], "reason": row["reason.ja"], "action": row["action.ja"]},
                    "vi": {"tittle": row["tittle.vi"], "description": row["description.vi"], "reason": row["reason.vi"], "action": row["action.vi"]},
                    "fr": {"tittle": row["tittle.fr"], "description": row["description.fr"], "reason": row["reason.fr"], "action": row["action.fr"]},
                },
                json_file,
                ensure_ascii=False,
                indent=4,
            )
